package com.wn.web;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


@Component
@Slf4j
@ServerEndpoint(value = "/WebSocketLink/{username}")
public class WebSocketServer {
    //静态变量，用来记录当前在线连接数
    private static int onlineCount = 0;
    //分段锁，用来存放每个客户对应的WebSocketServer对象
    private static Map<String, WebSocketServer> clients = new ConcurrentHashMap<>();
    //与某个客户的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private String username;

    @OnOpen
    public void onOpen(@PathParam("username")String username,Session session) throws IOException, EncodeException {
        System.out.println("----------------------------------------登录成功");
        this.username=username;
        this.session=session;
        addOnlineCount();

        log.info("有人连接！当前在线人数为"+getOnlineCount());
        clients.put(username,this);




    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        System.out.println(message);
        sendMessage(message);

    }



    @OnClose
    public void onClose() throws IOException {
        System.out.println("-------------------退出成功");
        clients.remove(username);
        subOnlineCount();
        log.info("有人退出连接！当前在线人数为"+getOnlineCount());
    }

    @OnError
    public void onError(Session session,Throwable error){
        log.error("websocket发生错误");
        error.printStackTrace();
    }

    public static void sendMessage(String message){

        for (WebSocketServer item : clients.values()){
            item.session.getAsyncRemote().sendText(message);
        }
    }

    /**
     * Base64解密
     */
    private static String decodeBase64(String str) throws UnsupportedEncodingException {
        byte[] decoded = Base64.getDecoder().decode(str);
        String decodeStr =  new String(decoded);
        return URLDecoder.decode(decodeStr,"utf-8");
    }

    /**
     * 加锁防止并发出现数目问题
     * */
    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        onlineCount++;
    }

    private static synchronized void subOnlineCount() {
        onlineCount--;
    }
}
